package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserActivityDaoImpl extends TempDataObjectDao<UserActivityConditionData> {

    public Map<Integer, List<UserActivityConditionData>> getUserActivityConditionDataMap(long userId, List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, List<UserActivityConditionData>> dataMap = new ConcurrentHashMap<>();
        if(null != activityIdList && activityIdList.size() > 0) {
            String sql = "select * from t_u_activity_condition where userId=? and activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
            try {
                getDb().setConnName(DbNameStrategy.getUserDb());
                call = getDb().getConnection().prepareCall(sql);
                call.setLong(1, userId);
                rs = call.executeQuery();
                while (rs.next()) {
                    UserActivityConditionData data = parse(rs);
                    if (!dataMap.containsKey(data.getActivityId())) {
                        dataMap.put(data.getActivityId(), new ArrayList<>());
                    }
                    dataMap.get(data.getActivityId()).add(data);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                getDb().closeConnection(call, rs);
            }
        }
        return dataMap;
    }

    public List<UserActivityConditionData> getUserActivityConditionDataList(int activityId, int rankNum){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=? group by userId order by value+0 desc limit " + rankNum;
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public List<UserActivityConditionData> getUserActivityConditionDataListByType(int activityId, int conditionType){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=?  and type = ?";
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, conditionType);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }


    public List<UserActivityConditionData> getUserActivityConditionDataList(int activityId, int conditionType, int rankNum){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=? and type=? group by userId order by value+0 desc limit " + rankNum;
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, conditionType);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public UserActivityConditionData getUserActivityConditionData(int activityId, long userId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=? and userId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setLong(2, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                return data;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public Map<Long, UserActivityConditionData> getUnionActivityUserConditionDataMap(int activityId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, UserActivityConditionData> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            String sql = "select * from t_u_activity_condition where activityId=?";
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);

            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataMap.put(data.getUserId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public UserActivityConditionData getUserActivityConditionData(int activityId, long userId, int conditionId){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=? and userId=? and conditionId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setLong(2, userId);
            call.setInt(3, conditionId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                return data;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public boolean updateUserActivityConditionDataState(UserActivityConditionData userActivityConditionData) {
        PreparedStatement call = null;
        String sql = "update t_u_activity_condition set isGetReward=? where userId=? and activityId=? and conditionId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setBoolean(i++, userActivityConditionData.isGetReward());
            call.setLong(i++, userActivityConditionData.getUserId());
            call.setInt(i++, userActivityConditionData.getActivityId());
            call.setInt(i++, userActivityConditionData.getConditionId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean addData(UserActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_activity_condition(userId,activityId,conditionId,preValue,value,isGetReward,modifyTime,param," +
                "type) values (?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getModifyTime());
            call.setString(i++, data.getParam());
            call.setInt(i++, data.getType());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }


    public boolean batchAdd(List<UserActivityConditionData> tempAddUserActivityConditionDatas) {
        boolean result = false;
        if (tempAddUserActivityConditionDatas.size() == 0) {
            return result;
        }

        // 设置写时间
        for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
            data.setBeginWriteTime();
        }

        String sql = "insert into t_u_activity_condition(userId,activityId,conditionId,preValue,value,isGetReward,modifyTime,param," +
                "type) values (?,?,?,?,?,?,?,?,?)";
        getDb().setConnName(DbNameStrategy.getUserDb());
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getActivityId()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getConditionId()));
            para.put(i++, new DbParameter(Types.VARCHAR, data.getPreValue().toString()));
            para.put(i++, new DbParameter(Types.VARCHAR, data.getValue().toString()));
            para.put(i++, new DbParameter(Types.BOOLEAN, data.isGetReward()));
            para.put(i++, new DbParameter(Types.BIGINT,data.getModifyTime()));
            para.put(i++, new DbParameter(Types.VARCHAR, data.getParam()));
            para.put(i++, new DbParameter(Types.INTEGER, data.getType()));
            mapList.add(para);
        }

        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            // 设置写入状态
            for (UserActivityConditionData data : tempAddUserActivityConditionDatas) {
                data.setNoneOption();
            }
            result = true;
        }
        return result;
    }

    @Override
    protected boolean updateData(UserActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "update t_u_activity_condition set preValue=?,value=?,isGetReward=?,modifyTime=?,param=?,type=? where userId=? and "
                + "activityId=? and conditionId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getModifyTime());
            call.setString(i++, data.getParam());
            call.setInt(i++, data.getType());
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UserActivityConditionData parseData(ResultSet rs) throws SQLException {
        UserActivityConditionData data = new UserActivityConditionData();
        data.setUserId(rs.getLong("userId"));
        data.setActivityId(rs.getInt("activityId"));
        data.setConditionId(rs.getInt("conditionId"));
        String value = rs.getString("preValue");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setPreValue(new BigInteger(value));
        }
        value = rs.getString("value");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        data.setGetReward(rs.getBoolean("isGetReward"));
        data.setModifyTime(rs.getLong("modifyTime"));
        data.setParam(rs.getString("param"));
        data.setType(rs.getInt("type"));
        return data;
    }

    public List<UserActivityConditionData> getUserActivityConditionDataListByUserIdAndType(int activityId, long userId, int conditionType) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_activity_condition where activityId=?  and userId = ? and  type = ?";
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setLong(2, userId);
            call.setInt(3, conditionType);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public Map<Integer, Map<Long, Map<Integer, List<UserActivityConditionData>>>> getActivityAllConditionData(List<Integer> activityIds) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Long, Map<Integer, List<UserActivityConditionData>>>> map = new ConcurrentHashMap<>();
        String sql = "select * from t_u_activity_condition where activityId in(" + StringUtils.listToString(activityIds, ",") + ")";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                if (!map.containsKey(data.getActivityId())) {
                    map.put(data.getActivityId(), new ConcurrentHashMap<>());
                }
                Map<Long, Map<Integer, List<UserActivityConditionData>>> userConditionMap = map.get(data.getActivityId());
                if (userConditionMap != null) {
                    if (!userConditionMap.containsKey(data.getUserId())) {
                        userConditionMap.put(data.getUserId(), new ConcurrentHashMap<>());
                    }
                    Map<Integer, List<UserActivityConditionData>> conditionMap = userConditionMap.get(data.getUserId());
                    if (conditionMap != null) {
                        if (!conditionMap.containsKey(data.getType())) {
                            conditionMap.put(data.getType(), new ArrayList<>());
                        }
                        conditionMap.get(data.getType()).add(data);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return map;
    }

    /**
     * 更新 condition值
     * @param activityId
     * @param userId
     * @param conditionType
     * @param value
     */
    public boolean updateUserActivityConditionData(int activityId, long userId, int conditionType, String value){
        PreparedStatement call = null;
        String sql = "update t_u_activity_condition set `value` =? where `userId`=? and `activityId`=? and `type`=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, value);
            call.setLong(i++, userId);
            call.setInt(i++, activityId);
            call.setInt(i++, conditionType);
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }


}
